<template>
  <div>
    <n-card :bordered="false" class="proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>

      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row: ListData) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        :scroll-x="1500"
      >
        <template #tableTitle>
          <div class="flex justify-between" style="width: 100%">
            <div class="">
              <n-button type="info" style="margin-right: 20px" @click="showModal('', true)">
                添加
              </n-button>
              <n-button @click="goUnits" type="info"> 单位列表 </n-button>
            </div>
            <div>
              <n-button @click="generateCode" type="info" class="mr-3"> 生成二维码 </n-button>
              <n-button @click="batchDownloadIamge" type="success"> 下载本页 </n-button>
            </div>
          </div>
        </template>
      </BasicTable>
    </n-card>
    <!-- 新增弹窗 -->
    <basicModal
      @register="modalRegister"
      ref="modalRef"
      class="basicModal"
      @on-ok="handleAddManage"
    >
      <template #default>
        <BasicForm @register="registerModal" :rules="rules" @reset="handleReset" class="basicForm">
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>
        </BasicForm>
      </template>
    </basicModal>
  </div>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';

  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import {
    getManageList,
    addManage,
    extinguisherChangeStatus,
    extinguisherDel,
    extinguisherEdit,
  } from '@/api/api';
  import { columns, ListData } from './columns';
  import { schemasManage, schemasManageModal, formattedDate } from '@/config/options';
  import { basicModal, useModal } from '@/components/Modal';
  import { PlusOutlined } from '@vicons/antd';
  import { useRouter } from 'vue-router';
  import { type FormRules } from 'naive-ui';
  import { nextTick } from 'process';
  import { useMessage, useDialog } from 'naive-ui';
  import JSZip from 'jszip';
  import FileSaver from 'file-saver';
  import { forEach } from 'lodash';
  import { ifError } from 'assert';
  const message = useMessage();
  const dialog = useDialog();
  const editEnd = () => {
    console.log(2);
  };
  const rules = {
    unit_id: {
      required: true,
      message: '请选择',
      trigger: 'change',
      type:'Number'
    },
    site: {
      required: true,
      message: '请输入放置点',
      trigger: 'input',
    },
    workshop_id: {
      required: true,
      message: '请选择',
      trigger: 'change',
      type:'Number'
    },
    product_name: {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
    factory: {
      required: true,
      message: '请输入',
      trigger: 'input',
    },
    model: {
      required: true,
      message: '请输入',
      trigger: 'input',
    },
    produce_time: {
      type: 'date',
      required: true,
      message: '请选择',
      trigger: 'change',
    },
    scrap_time: {
      type: 'date',
      required: true,
      message: '请选择',
      trigger: 'change',
    },
    repair_time: {
      type: 'date',
      required: true,
      message: '请选择',
      trigger: 'change',
    },
    next_repair_time: {
      type: 'date',
      required: true,
      message: '请选择',
      trigger: 'change',
    },
    pressure_time: {
      type: 'date',
      required: true,
      message: '请选择',
      trigger: 'change',
    },
    next_pressure_time: {
      type: 'date',
      required: true,
      message: '请选择',
      trigger: 'change',
    },
    powder_time: {
      type: 'date',
      required: true,
      message: '请选择',
      trigger: 'change',
    },
    next_powder_time: {
      type: 'date',
      required: true,
      message: '请选择',
      trigger: 'change',
    },
    annual_check: {
      type: 'date',
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  };
  const isAdd = ref(true);
  const onEditChange = () => {
    console.log(2);
  };
  const xiugai = () => {
    console.log(schemasManageModal);
    schemasManageModal[1].componentProps.options = [{ label: '1', value: 1 }];
  };
  const router = useRouter();
  const formRef: any = ref(null);
  const actionRef = ref();

  const formBtnLoading = ref(false);
  const formParams = reactive({
    name: '',
    role: null,
    droit: true,
  });

  const actionColumn = reactive({
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'text',
        actions: [
          {
            label: '编辑',
            onClick: showModal.bind(null, record, false),
          },
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
          },
        ],
      });
    },
  });

  const [register, { getFieldsValue }] = useForm({
    gridProps: { cols: '2 s:2 m:2 l:3 xl:4 2xl:4' },
    schemas: schemasManage,
    collapsedRows: 2,
    isFull: false,
  });
  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({
    title: '添加/编辑',
  });
  const [registerModal, { submit }] = useForm({
    gridProps: { cols: 2 },
    isFull: false,
    layout: 'horizontal',
    submitButtonText: '提交预约',
    showActionButtonGroup: false,
    schemas: schemasManageModal,
  });
  const modalRef = ref(null);
  const datalist = ref(null);
  function showModal(record, flag) {
    flag ? (isAdd.value = true) : (isAdd.value = false);
    let names = [];
    if (!flag) {
      id.value = record.id;
      var produce_time = Date.parse(record.produce_time); //生产日期
      var repair_time = Date.parse(record.repair_time); //维修日期
      var pressure_time = Date.parse(record.pressure_time); //水压试测日期
      var powder_time = Date.parse(record.powder_time); //粉剂更换日期
      var annual_check = Date.parse(record.annual_check); //年检日期
      var scrap_time = Date.parse(record.scrap_time); //报废日期
      var next_repair_time = Date.parse(record.next_repair_time); //下次维修日期
      var next_pressure_time = Date.parse(record.next_pressure_time); //下次水压试验日期
      var next_powder_time = Date.parse(record.next_powder_time); //下次粉剂更换时间

      names = [
        record.unit_id,
        record.site,
        record.workshop_id,
        record.product_name,
        record.factory,
        record.model,
        produce_time,
        scrap_time,
        repair_time,
        next_repair_time,
        pressure_time,
        next_pressure_time,
        powder_time,
        next_powder_time,
        annual_check,
      ];
    }
    schemasManageModal.forEach((obj, index) => {
      obj.defaultValue = names[index];
    });
    openModal();
  }
  // 添加灭火器
  const handleAddManage = async () => {
    const formRes = await submit();
    console.log(formRes);
    if (formRes) {
      // 发送添加请求
      if (isAdd.value) {
        add(formRes);
      } else {
        handleEdit(formRes);
      }
    } else {
      message.error('验证失败，请填写完整信息');
      setSubLoading(false);
    }
  };
  const add = async (formRes) => {
    formRes.next_powder_time = formattedDate(formRes.next_powder_time);
    formRes.next_pressure_time = formattedDate(formRes.next_pressure_time);
    formRes.next_repair_time = formattedDate(formRes.next_repair_time);
    formRes.powder_time = formattedDate(formRes.powder_time);
    formRes.pressure_time = formattedDate(formRes.pressure_time);
    formRes.produce_time = formattedDate(formRes.produce_time);
    formRes.scrap_time = formattedDate(formRes.scrap_time);
    formRes.annual_check = formattedDate(formRes.annual_check);
    formRes.repair_time = formattedDate(formRes.repair_time);
    await addManage({ ...formRes })
      .then((res) => {
        setSubLoading(false);
        closeModal();
        reloadTable();
        message.info('添加成功');
      })
      .catch((err) => {
        setSubLoading(false);
      });
  };
  const loadDataTable = async (res) => {
    const data = await getManageList({ ...getFieldsValue(), ...res });
    datalist.value = data;
    return data;
  };
  function reloadTable() {
    actionRef.value.reload();
  }
  // 删除账号
  function handleDelete(record) {
    dialog.warning({
      title: '提示',
      content: `确定删除吗？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        extinguisherDel({ id: record.id }).then((res) => {
          console.log(res);
          reloadTable();
          message.success('删除成功');
        });
      },
      onNegativeClick: () => {},
    });
  }
  function handleSubmit(values: Recordable) {
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }
  const goUnits = () => {
    router.push('units');
  };
  function handleForbidden(record) {
    let status = record.status ? '启用' : '禁用';
    dialog.warning({
      title: '提示',
      content: `是否确认${status}？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        let result = await extinguisherChangeStatus({
          id: record.id,
          status: record.status * 1 ? 0 : 1,
        });
        console.log(result);
        message.success(result.status ? '已禁用' : '已启用');
        reloadTable();
      },
      onNegativeClick: () => {},
    });
  }
  const id = ref(0); //账号id
  // 编辑灭火器
  const handleEdit = async (formRes: any) => {
    formRes.produce_time = formattedDate(formRes.produce_time);
    formRes.repair_time = formattedDate(formRes.repair_time);
    formRes.pressure_time = formattedDate(formRes.pressure_time);
    formRes.powder_time = formattedDate(formRes.powder_time);
    formRes.annual_check = formattedDate(formRes.annual_check);
    formRes.scrap_time = formattedDate(formRes.scrap_time);
    formRes.next_repair_time = formattedDate(formRes.next_repair_time);
    formRes.next_pressure_time = formattedDate(formRes.next_pressure_time);
    formRes.next_powder_time = formattedDate(formRes.next_powder_time);
    await extinguisherEdit({ ...formRes, id: id.value })
      .then((res) => {
        setSubLoading(false);
        closeModal();
        reloadTable();
        message.info('修改成功');
      })
      .catch((err) => {
        setSubLoading(false);
      });
  };
  // 下载多张图片
  const batchDownloadIamge = () => {
    var code_path_list = datalist.value.data.map((item) => {
      return item.code_path;
    });
    //压缩包名
    var blogTitle = '打包图片';
    var zip = new JSZip();
    var imgs = zip.folder(blogTitle);
    var baseList = [];
    // 要下载图片的url
    var arr = code_path_list;
    for (var i = 0; i < arr.length; i++) {
      let image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous');
      image.onload = function () {
        let canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext('2d');
        context.drawImage(image, 0, 0, image.width, image.height);
        let url = canvas.toDataURL(); // 得到图片的base64编码数据
        canvas.toDataURL('image/png');
        baseList.push(url.substring(22)); // 去掉base64编码前的     data:image/png;base64,
        if (baseList.length === arr.length && baseList.length > 0) {
          for (let k = 0; k < baseList.length; k++) {
            imgs.file(`图片${Number(k) + 1}.png`, baseList[k], { base64: true });
          }
          zip.generateAsync({ type: 'blob' }).then(function (content) {
            // see FileSaver.js
            FileSaver.saveAs(content, blogTitle + '.zip');
          });
        }
      };
      image.src = arr[i];
    }
  };
  // 生成二维码
  const generateCode = () => {};
</script>

<style lang="less">
  .n-dialog.n-modal {
    width: 600px !important;
  }
</style>
